#pragma once
#include <iostream>
#include <memory>
#include "Socket.hpp"
#include "Connection.hpp"
#include "InitAddr.hpp"
#include "Reactor.hpp"
#include "IOservice.hpp"
#include "Log.hpp"
#include "Calculator.hpp"


using namespace SocketModule;
using namespace LogModule;

class Listener : public Connection
{
public:
	Listener(int post) : _post(post), _listensock(std::make_unique<TcpSocket>())
	{
		_listensock->BulidTcpserverMethod(_post);
		Setsockfd(_listensock->Fd());
		Setevents(EPOLLIN | EPOLLET);
	}
	virtual void Sender() override {}
	virtual void Recver() override
	{
		while (true)
		{
			Inetaddr client_addr;
			int aerron = 0;
			int newsockfd = _listensock->SocketAccept(&client_addr,&aerron);
			if (newsockfd > 0)
			{
				LOG(LogLevel::DEBUG) << "Accepter success: " << newsockfd;
				 // 普通的文件描述符，处理IO的，也是connection！
                // 2. sockfd包装成为Connection！
				auto conn = std::make_shared<IOService>(newsockfd);
				conn->RegisterOnMessage(HandlerRequest); // 处理函数
				GetOwner()->insertConnection(conn);
			}
			else
			{
				if (aerron == EAGAIN || aerron == EWOULDBLOCK) // 
				{
					LOG(LogLevel::DEBUG) << "accetper all connection ... done";
					break;
				}
				else if(aerron == EINTR) // 	
				{
					LOG(LogLevel::DEBUG) << "accetper intr by signal, continue";
					 continue;
				}
				else
				{
					LOG(LogLevel::ERROR) << "accetper error";
					break;
				}
			}
		}
	}
	virtual void Excepter() override 
	{
		LOG(LogLevel::ERROR) << "listener excepter";
	}

	int Sockfd()
	{
		return _listensock->Fd();
	}
	~Listener()
	{
	}

private:
	std::unique_ptr<SocketModule::Socket> _listensock;
	int _post;
};